package com.hcb.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.adapter.AdapterAddContacts;
import com.hcb.app911.AddContactActivity;
import com.hcb.app911.ListPhoneNumberActivity;
import com.hcb.app911.MainActivity;
import com.hcb.app911.R;
import com.hcb.app911.RegisterActivity;
import com.hcb.app911.RegisterActivity.VerySlowTaskExits;
import com.hcb.common.ActionEvent;
import com.hcb.constants.Constants;
import com.hcb.controller.ContactController;
import com.hcb.dto.ContactsDTO;
import com.hcb.dto.CustomerDTO;
import com.hcb.model.utils.CustomerModel;
import com.hcb.webservice.InternetUtils;
import com.hcb.webservice.ServiceHandler;
import com.hcb.webservice.WebService;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EmergencyContactsFragment extends Fragment implements
		OnClickListener {
	ListView lvContacts;
	Button btnAdd, btnSave, btnSkip;
	AdapterAddContacts adapter;
	ArrayList<Object> arrData;
	public static final int PICK_CONTACT = 1001;
	Dialog dialog, dialogContact;
	AnimationDrawable frameAnimation;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fagment_emergency_contacts,
				container, false);
		((MainActivity)this.getActivity()).getImgDetail().setImageResource(R.drawable.mydetail);
		((MainActivity)this.getActivity()).getImgHome().setImageResource(R.drawable.icon);
		lvContacts = (ListView) rootView.findViewById(R.id.lvContacts);

		View fotter = inflater.inflate(R.layout.fotter_contacts, null, false);
		View header = inflater.inflate(R.layout.header_emergency_contacts,
				null, false);
		btnAdd = (Button) fotter.findViewById(R.id.btnAdd);
		btnSave = (Button) rootView.findViewById(R.id.btnSave);
		btnSkip = (Button) rootView.findViewById(R.id.btnSkip);
		btnAdd.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		btnSkip.setOnClickListener(this);
		lvContacts.addFooterView(fotter);
		lvContacts.addHeaderView(header);
		// lvContacts.setAdapter(null);
		arrData = new ArrayList<Object>();
		adapter = new AdapterAddContacts(getActivity(),
				R.layout.adapter_emergency_contacts, arrData);
		lvContacts.setAdapter(adapter);
		getContact();

		return rootView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btnAdd:

			dialogContact = new Dialog(getActivity(),
					android.R.style.Theme_Translucent);
			dialogContact.requestWindowFeature(Window.FEATURE_NO_TITLE);

			dialogContact.setCancelable(true);
			dialogContact.setContentView(R.layout.dialog_contacts);
			Button btnSelect = (Button) dialogContact
					.findViewById(R.id.btnSelect);
			Button btntypeing = (Button) dialogContact
					.findViewById(R.id.btntypeing);
			TextView txtNamedialog = (TextView) dialogContact
					.findViewById(R.id.txtNamedialog);
			txtNamedialog.setText("choose the type of contact.");

			btnSelect.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),
							ListPhoneNumberActivity.class);

					startActivityForResult(intent, 1000);
					dialogContact.dismiss();
				}
			});
			btntypeing.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(),
							AddContactActivity.class);

					startActivityForResult(intent, 1000);
					dialogContact.dismiss();

				}
			});

			dialogContact.show();

			break;
		case R.id.btnSave:
			if (InternetUtils.getInstance().isConnectingToInternet(
					getActivity())) {
				btnSave.setBackgroundResource(R.drawable.savef);
				ContactsDTO dto = new ContactsDTO();
				new VerySlowTaskPost(dto).execute();
			} else {
				Toast.makeText(getActivity(),
						"No network please connect network", Toast.LENGTH_LONG)
						.show();
			}
			break;

		case R.id.btnSkip:
			Fragment fragment = new HomeFragment();
			FragmentManager fragmentManager = getActivity()
					.getSupportFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.frame_container, fragment).commit();
			break;
		default:
			break;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1000:
			if (resultCode == Activity.RESULT_OK) {
				btnSave.setBackgroundResource(R.drawable.save);
				ContactsDTO dto = (ContactsDTO) data
						.getSerializableExtra("myobj");
				if (adapter.getCount() >= 2) {
					Toast.makeText(getActivity(),
							"phone number max please remove phone numbe",
							Toast.LENGTH_LONG).show();
					// adapter.remove(arrData.get(0));
					//
					// arrData.add(dto);
					// adapter.notifyDataSetChanged();
					// ActionEvent e = new ActionEvent(this,
					// Constants.INSERT_CONTACT,
					// dto, null);
					// ContactController.getInstance().handleViewEvent(e);

				} else {

					arrData.add(dto);
					adapter.notifyDataSetChanged();
					ActionEvent e = new ActionEvent(this,
							Constants.INSERT_CONTACT, dto, null);
					ContactController.getInstance().handleViewEvent(e);
				}

			}
			break;

		default:
			break;
		}
	}

	public class VerySlowTaskPost extends AsyncTask<Void, Void, Void> {
		String result;
		ContactsDTO contact;

		public VerySlowTaskPost(ContactsDTO _contact) {
			contact = _contact;
			dialog = new Dialog(getActivity(), R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {
			CustomerModel model = CustomerModel.getInstance();
			CustomerDTO cus = model.getCustomer(getActivity());
			for (Object ob : arrData) {
				ContactsDTO con = (ContactsDTO) ob;
				if (adapter.getPosition(con) == 0) {

					ServiceHandler sh = new ServiceHandler();
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("query",
							Constants.UPDATE_CUSTOMER_CONTACT_ONE));
					nameValuePairs.add(new BasicNameValuePair("api_secret_key",
							Constants.API_KEY));
					nameValuePairs.add(new BasicNameValuePair(
							Constants.CUSTOMER_ID, cus.getCustomer_id()));
					nameValuePairs
							.add(new BasicNameValuePair(
									Constants.NOMINATED_CONTACT_NAME_ONE, con
											.getName()));
					nameValuePairs.add(new BasicNameValuePair(
							Constants.NOMINATED_CONTACT_NUMBER_ONE, con
									.getNumber()));

					String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
							ServiceHandler.POST, nameValuePairs);
					if (jsonStr != null) {
						try {
							JSONObject object;
							object = new JSONObject(jsonStr);
							String value = object.getString("result");
							String contactid = object.getString("data_body");
							// customer.setCustomer_id(customerid);
							if (value.contains("success")) {

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					} else {
						// Log.e("ServiceHandler",
						// "Couldn't get any data from the url");
					}
				} else if (adapter.getPosition(con) == 1) {
					ServiceHandler sh = new ServiceHandler();
					List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					nameValuePairs.add(new BasicNameValuePair("query",
							Constants.UPDATE_CUSTOMER_CONTACT_TWO));
					nameValuePairs.add(new BasicNameValuePair("api_secret_key",
							Constants.API_KEY));
					nameValuePairs.add(new BasicNameValuePair(
							Constants.CUSTOMER_ID, cus.getCustomer_id()));
					nameValuePairs
							.add(new BasicNameValuePair(
									Constants.NOMINATED_CONTACT_NAME_TWO, con
											.getName()));
					nameValuePairs.add(new BasicNameValuePair(
							Constants.NOMINATED_CONTACT_NUMBER_TWO, con
									.getNumber()));

					String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
							ServiceHandler.POST, nameValuePairs);
					if (jsonStr != null) {
						try {
							JSONObject object;
							object = new JSONObject(jsonStr);
							String value = object.getString("result");
							String contactid = object.getString("data_body");
							// customer.setCustomer_id(customerid);
							if (value.contains("success")) {

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					} else {
						// Log.e("ServiceHandler",
						// "Couldn't get any data from the url");
					}
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			btnSave.setBackgroundResource(R.drawable.save);

		}

	}

	private class updateCustomerContact implements Runnable {

		ContactsDTO contact;
		Context contextRunnable;

		public updateCustomerContact(ContactsDTO cont, Context context) {
			contact = cont;
			contextRunnable = context;
		}

		@Override
		public void run() {
			for (Object ob : arrData) {
				ContactsDTO con = (ContactsDTO) ob;
				if (adapter.getPosition(con) == 0) {
					String url = Constants.URL_SERVICE
							+ "updateCustomerContactOne";
					url += "/api_secret_key/" + "3832_2hd3hdiwyu34eyeuidhd_948";
					url += "/query/" + "updateCustomerContactOne";
					url += "/customer_id/" + "35";
					url += "/nominated_conact_name_one/" + con.getName();
					url += "/nominated_conact_number_one/" + "+2348139070432"; // con.getNumber().trim();
					String jsonResponse = WebService.getInstance().get(url);

					try {
						JSONObject object;
						object = new JSONObject(jsonResponse);
						String value = object.getString("result");
						String contactid = object.getString("data_body");
						// customer.setCustomer_id(customerid);
						if (value.contains("success")) {

							// ActionEvent e = new ActionEvent(
							// RegisterActivity.this,
							// Constants.INSERT_CUSTOMER, customer, null);
							// CustomerController.getInstance().handleViewEvent(e);
							//
							// Intent intent = new Intent(contextRunnable,
							// ValidationActivity.class);
							// // Bundle bundle = new Bundle();
							// // bundle.putSerializable("customer", customer);
							// // intent.putExtras(bundle);
							// startActivity(intent);
							// finish();
						}
					} catch (JSONException e) {
						e.printStackTrace();
						return;
					}

				} else if (adapter.getPosition(con) == 1) {
					String url = Constants.URL_SERVICE
							+ "updateCustomerContactTwo";
					url += "/api_secret_key/" + "3832_2hd3hdiwyu34eyeuidhd_948";
					url += "/query/" + "updateCustomerContactTwo";
					url += "/customer_id/" + "35";
					url += "/nominated_conact_name_two/" + con.getName();
					url += "/nominated_conact_number_two/" + "+2348139070455";// con.getNumber().trim();

					String jsonResponse = WebService.getInstance().get(url);

					try {
						JSONObject object;
						object = new JSONObject(jsonResponse);
						String value = object.getString("result");
						String contactid = object.getString("data_body");
						// customer.setCustomer_id(customerid);
						if (value.contains("success")) {

						}
					} catch (JSONException e) {
						e.printStackTrace();
						return;
					}
				}

			}

			// try {
			// JSONObject object;
			// object = new JSONObject(jsonResponse);
			// String value = object.getString("result");
			// String customerid = object.getString("data_body");
			// customer.setCustomer_id(customerid);
			// if (value.contains("success")) {
			//
			// ActionEvent e = new ActionEvent(RegisterActivity.this,
			// Constants.INSERT_CUSTOMER, customer, null);
			// CustomerController.getInstance().handleViewEvent(e);
			//
			// Intent intent = new Intent(contextRunnable,
			// ValidationActivity.class);
			// // Bundle bundle = new Bundle();
			// // bundle.putSerializable("customer", customer);
			// // intent.putExtras(bundle);
			// startActivity(intent);
			// finish();
			// } else {
			// if(customerid.equalsIgnoreCase("This mobile number is already registered!")){
			//
			// }
			// String url1 = Constants.URL_SERVICE + "sendVerificationCode";
			// url1 += "/api_secret_key/"
			// + "3832_2hd3hdiwyu34eyeuidhd_948";
			// url1 += "/query/" + "sendVerificationCode";
			// url1 += "/mobile_number/" + customer.getMobile_number();
			// String jsonResponse1 = WebService.getInstance().get(
			// url1);
			// try {
			// JSONObject object1;
			// object1 = new JSONObject(jsonResponse1);
			// String value1 = object1.getString("result");
			// if (value1.contains("success")) {
			// Intent intent = new Intent(contextRunnable,
			// ValidationActivity.class);
			// startActivity(intent);
			// finish();
			// }
			//
			// } catch (Exception e) {
			// e.printStackTrace();
			// }
			//
			// }
			// } catch (JSONException e) {
			// e.printStackTrace();
			// return;
			// }

		}
	}

	public void getContact() {
		ActionEvent e = new ActionEvent(this, Constants.GET_CONTACT, null, null);
		ContactController.getInstance().handleViewEvent(e);
	}

	ArrayList<ContactsDTO> newArr;

	public void handleControllerViewEvent(ActionEvent e) {
		switch (e.action) {
		case Constants.GET_CONTACT:
			newArr = (ArrayList<ContactsDTO>) e.viewData;
			new VerySlowTask(newArr).execute();
			break;
		default:
			break;
		}
	}

	public class VerySlowTask extends AsyncTask<String, Object, Void> {
		List<ContactsDTO> _newArr;

		public VerySlowTask(List<ContactsDTO> arr) {
			_newArr = arr;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			try {
				for (int i = 0; i < _newArr.size(); i++) {
					publishProgress(_newArr.get(i));

				}
			} catch (Exception e) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			arrData.add(values[0]);

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
		}

	}

}
